<script setup lang='ts'>
import type { FieldValues, PlusColumn } from 'plus-pro-components'

import { useAddOrUpdateSpecification } from '@fl/api/fit-old-api'
import { SubmitBtn } from '@fl/components'
import UpdatedOss from '@fl/components/upLoad-oss.vue'

const props = withDefaults(defineProps<{
    data?: any
}>(), {
    data: {},
})

const emits = defineEmits(['addSpecificationData', 'refreshSpecificationData'])
const form = ref()
const visible = ref(false)
const { data } = toRefs(props)
const id = defineModel<string>('id', { required: true })
const isAddOrEdit = ref<string>()
const productId = defineModel<string>('productId', { required: true })
console.log('table-add：', id.value, productId.value, data.value)

const title = computed(() => {
    return isAddOrEdit.value === 'edit' ? '编辑产品规格' : '新增产品规格'
})

const { isPending, mutate } = useAddOrUpdateSpecification()

const initialState = {
    fileUrl: '',
    formName: '',
    id: '',
    introduce: '',
    isDeleted: '0',
    price: 0,
    productId: '',
    remark: '',
    sort: 0,
}

const formValues = ref<FieldValues>({ ...initialState })
watchEffect(() => {
    console.log('table-add：isAddOrEdit', isAddOrEdit.value)
    if (isAddOrEdit.value === 'edit')
        formValues.value = data.value
    else
        formValues.value = { ...initialState }
})

function reset() {
    console.log('add - reset')
    id.value = ''
    form.value.formInstance.resetFields()
    formValues.value = { ...initialState }
}

function handleAddOpen(type) {
    isAddOrEdit.value = type
    visible.value = true
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 12,
        },
        label: '规格名称',
        prop: 'formName',
    },
    {
        colProps: {
            span: 12,
        },
        label: '规格介绍',
        prop: 'introduce',
    },
    {
        label: '是否删除',
        options: [
            {
                label: '是',
                value: '1',
            },
            {
                label: '否',
                value: '0',
            },
        ],
        prop: 'isDeleted',
        valueType: 'radio',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: { min: 1, precision: 0, step: 1 },
        label: '排序',
        prop: 'sort',
        valueType: 'input-number',
    },
    {
        fieldProps: {
            autosize: { maxRows: 5, minRows: 3 },
        },
        label: '备注',
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 12,
        },
        fieldSlots: {
            append: () => '元',
        },
        label: '产品价格',
        prop: 'price',
    },
    {
        label: '产品图片',
        prop: 'fileUrl',
    },
]

const rules = {
    fileUrl: [
        {
            message: '请上传产品图片',
            required: true,
        },
    ],
    formName: [
        {
            message: '请填写规格名称',
            required: true,
        },
    ],
    introduce: [
        {
            message: '请填写规格介绍',
            required: true,
        },
    ],
    price: [
        {
            message: '请输入价格',
            required: true,
        },
    ],
}

// 提交规格
async function confirm() {
    const valid = await form.value.formInstance.validate()
    if (valid) {
        if (productId.value) {
            // 1.编辑、有productId
            console.log('formValues', formValues.value)
            const params = {
                ...formValues.value,
                productId: productId.value,
            }
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                    // 刷新编辑页规格列表
                    emits('refreshSpecificationData', true)
                    cancel()
                },
            })
        }
        else {
            // 2.新增、无productId
            console.log('新增单条数据', formValues.value)
            emits('addSpecificationData', formValues.value)
            cancel()
        }
    }
}

function cancel() {
    visible.value = false
}

function uploadSuccess(data) {
    formValues.value.fileUrl = data?.url
}

defineExpose({
    handleAddOpen,
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <!-- <ElSkeleton v-if="isLoading"
                    animated
        /> -->
        <!-- v-else -->
        <PlusForm ref="form"
                  v-model="formValues"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-fileUrl>
                <UpdatedOss v-model="formValues.fileUrl"
                            accept=".png,.jpg,.jpeg"
                            @success="uploadSuccess"
                />
            </template>
        </plusform>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
